package com.lry.sso.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.lry.sso.common.entity.response.ResultData;
import com.lry.sso.common.entity.response.Ret;
import com.lry.sso.common.exception.SysErrorEnum;
import com.lry.sso.common.exception.SysInvocationException;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import javax.servlet.http.HttpServletResponse;

/**
 * @author 李瑞益
 * @date 2020-02-12 12:38
 */
//@Component
public class ErrorFilter extends SendErrorFilter {

    private static final Logger log = LoggerFactory.getLogger(ErrorFilter.class);

    @Override
    public Object run() {
        try {
            RequestContext ctx = RequestContext.getCurrentContext();
            SendErrorFilter.ExceptionHolder exception = this.findZuulException(ctx.getThrowable());
exception.getThrowable().printStackTrace();
            ResultData error = null;
            if (exception.getThrowable() instanceof SysInvocationException) {
                error = Ret.error(((SysInvocationException) exception).getError());
            }else{
                error = Ret.error(SysErrorEnum.SYSTEM.code(), exception.getThrowable().getMessage());
            }
            log.error("网关异常信息：{}",error);

            HttpServletResponse response = ctx.getResponse();
            response.getOutputStream().write(JSON.toJSONString(error).getBytes());
        } catch (Exception var5) {
            ReflectionUtils.rethrowRuntimeException(var5);
        }
        return null;
    }

}
